import { defineStore } from "pinia";

import { ref, computed } from "vue";

export const useCalendarStore = defineStore('calendar', () => {
    const currentMonth = ref(8);
    // 日历当前显示年份
    const currentYear = ref(2024);
    // 日历当前选中的日期
    const currentDate = ref(8);

    // 获取日历列表数据
    const dataList = computed(() => {
        //获取当前月份有几天
        const monthDays = new Date(currentYear.value, currentMonth.value, 0).getDate();
        //获取上个月有几天
        const lastMonthDays = new Date(currentYear.value, currentMonth.value - 1, 0).getDate();
        //获取当前月份第一天是星期几 :范围1-7
        const firstDayWeek = new Date(currentYear.value, currentMonth.value - 1, 1).getDay() || 7;
        //初始化数组
        const data = [];
        //补全上个月的日期
        for (let i = 1; i < firstDayWeek; i++) {
            data.push({
                tag: 'last',
                date: lastMonthDays - firstDayWeek + i + 1
            });
        }
        for (let i = 1; i <= monthDays; i++) {
            data.push({
                tag: 'current',
                date: i
            });
        }
        //补全到42个元素
        for (let i = 1; i <= 42 - monthDays - (firstDayWeek - 1); i++) {
            data.push({
                tag: 'next',
                date: i
            });
        }
        return data;
    });

    //更新日历当前显示月份
    const setCurrentMonth = (month) => {
        if (month < 1) {
            month = 12;
            setCurrentYear(currentYear.value - 1);
        } else if (month > 12) {
            month = 1;
            setCurrentYear(currentYear.value + 1);
        }
        currentMonth.value = month;
    };
    //更新日历当前显示年份
    const setCurrentYear = (year) => {
        currentYear.value = year;
    };
    //更新日历当前选中的日期
    const setCurrentDate = (date) => {
        currentDate.value = date;
    };

    return {
        dataList,
        currentMonth,
        currentYear,
        currentDate,
        setCurrentMonth,
        setCurrentYear,
        setCurrentDate
    };
});